package main

import (
	"fmt"
	"github.com/go-kit/kit/log"
	"google.golang.org/grpc"
	mylog "log"
	"mytest/kitcli/user/pkg/endpoint"
	"mytest/kitcli/user/pkg/service"
	transportUser "mytest/kitcli/user/pkg/transport/grpc"
	pbUser "mytest/kitcli/user/pkg/transport/grpc/pb"
	"net"
	"os"
)

const (
	ServiceHostPort = "0.0.0.0:9902"
)

func main() {

	defer func() {
		if err := recover(); err != nil {
			mylog.Println("捕获到了宕机")
		}
	}()

	//kit生成模块:
	//kit new service user

	//定义grpc接口
	//type UserService interface {
	//	GetUserList(ctx context.Context, request interface{}) (result interface{}, err error)
	//	AddUser(ctx context.Context, request interface{}) (result interface{}, err error)
	//	UpdateUser(ctx context.Context, request interface{}) (result interface{}, err error)
	//	DeleteUser(ctx context.Context, request interface{}) (result interface{}, err error)
	//	FindUser(ctx context.Context, request interface{}) (result interface{}, err error)
	//}

	//kit生成grpc代码:
	//kit generate service user -t grpc --dmw
	l, err := net.Listen("tcp", ServiceHostPort)
	if err != nil {
		panic(fmt.Sprintf("Failed to listen: %v", err))
	}
	var logger log.Logger
	{
		logger = log.NewLogfmtLogger(os.Stderr)
		logger = log.With(logger, "ts", log.DefaultTimestamp)
		logger = log.With(logger, "caller", log.DefaultCaller)
	}
	middlewares := []service.Middleware{service.LoggingMiddleware(logger)}
	userService := service.New(middlewares)
	endpointUser := endpoint.New(userService, nil)

	userServer := transportUser.NewGRPCServer(endpointUser)

	s := grpc.NewServer()

	pbUser.RegisterUserServer(s, userServer)

	fmt.Println("Listen on " + ServiceHostPort)
	if err := s.Serve(l); err != nil {
		panic(fmt.Sprintf("Failed to serve: %v", err))
	}

}
